package su.user.module;

/**
 * 用户管理，包括业务员、供货商、发货站、客户
 */
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.kuakao.core.dto.PagerDTO;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import su.tool.AreaUtil;
import su.tool.RegexUtil;
import su.tool.SuIntUtils;
import su.user.dto.UserCustomerDto;
import su.user.entity.UserCustomer;
import su.user.entity.UserFhz;
import su.user.entity.UserGhs;
import su.user.entity.UserYwy;
import su.user.service.UserService;
import su.user.util.YwyCache;
@Controller
@RequestMapping("/admin/user")
public class UserServlet {

	@Autowired
	private UserService userService;
	
	@Autowired
	private YwyCache ywyCache;

	protected final Log log = LogFactory.getLog(getClass());
	//===============业务员
	/**
	 * 业务员管理首页
	 * @param request
	 * @param model
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("ywy_index")
	public String ywyIndex(HttpServletRequest request, Model model,PagerDTO dto){
		List<UserYwy> list = userService.searchYwy(dto);
		model.addAttribute("list", list);

		model.addAttribute("_page", dto);
		return "/maintain/user/ywy_index";
	}

	/**
	 * 到 保存/修改 业务员信息
	 * @param request
	 * @param model
	 * @param ywy
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("to_edit_ywy")
	public String toEditYwy(HttpServletRequest request, Model model) {
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	UserYwy ywy = userService.getYwyById(id);
            model.addAttribute("ywy", ywy);
        }
		return "/maintain/user/ywy_edit";
	}
	/**
	 * 保存
	 * @param request
	 * @param model
	 * @param ywy
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("do_save_ywy")
	public String doSaveYwy(HttpServletRequest request, Model model,UserYwy ywy){
		ywy.setJianpin(ywy.getJianpin().trim());
		ywy.setYwydesc(ywy.getYwydesc().trim());
		ywy.setYwyname(ywy.getYwyname().trim());
		String res = "";
		try {
			userService.saveYwy(ywy);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/user/ywy_index.action";
	}
	/**
	 * 删除业务员信息
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("do_remove_ywy")
	public void doRemoveYwy(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer==null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				userService.removeYwy(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	
	//=============供货商
	/**
	 * 供货商
	 */
	@RequestMapping("ghs_index")
	public String ghsIndex(HttpServletRequest request, Model model,PagerDTO dto){
		List<UserGhs> list = userService.searchGhsByPage(dto);
		model.addAttribute("list", list);

		model.addAttribute("_page", dto);
		return "/maintain/user/ghs_index";
	}
	/**
	 * 到 保存/修改 供货商信息
	 * @param request
	 * @param model
	 * @param ywy
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("to_edit_ghs")
	public String toEditGhs(HttpServletRequest request, Model model){
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	UserGhs baseinfo = userService.getGhsById(id);
            model.addAttribute("baseinfo", baseinfo);
        }
		return "/maintain/user/ghs_edit";
	}
	/**
	 * 保存
	 * @param request
	 * @param model
	 * @param ghs
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("do_save_ghs")
	public String doSaveGhs(HttpServletRequest request, Model model,UserGhs ghs){
		ghs.setGhsdesc(ghs.getGhsdesc().trim());
		ghs.setGhsname(ghs.getGhsname().trim());
		ghs.setJianpin(ghs.getJianpin().trim());
		String res = "";
		try {
			userService.saveGhs(ghs);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/user/ghs_index.action";
	}
	/**
	 * 删除供货商信息
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("do_remove_ghs")
	public void doRemoveGhs(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				userService.removeGhs(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	/**
	 * 根据id或简拼得到供货商列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("search_user_ghs")
	public void searchUserGhs(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		
		String q = request.getParameter("term");
		if(StringUtils.isBlank(q) || q.length()>6){//查询条件为空或字符数大于6(显示的汉字)时不予查询
			writer.print("");
			writer.flush();
			writer.close();
			return;
		}
		//System.out.println("aa==="+q);
		List list = new ArrayList();
		Map<String ,String> map;
		PagerDTO dto = new PagerDTO();
		//
		if(RegexUtil.isNumeric(q)){//id
			dto.setS1(q);
		}else{//简拼
			dto.setS2(q);
		}
		List<UserGhs> ghsList = userService.searchGhsByPage(dto);
		if(ghsList!=null && !ghsList.isEmpty()){
			for(UserGhs ghs : ghsList){
				map=new HashMap<String, String>();
				map.put("id", ghs.getId()+"");
				map.put("label", ghs.getGhsname());
				list.add(map);
			}
		}

		writer.print(JSONArray.fromObject(list.toArray()).toString());
		writer.flush();
		writer.close();
    }
	//===========================发货站
	/**
	 * 发货站
	 */
	@RequestMapping("fhz_index")
	public String fhzIndex(HttpServletRequest request, Model model,PagerDTO dto){
		List<UserFhz> list = userService.searchFhz(dto);
		model.addAttribute("list", list);

		model.addAttribute("_page", dto);
		return "/maintain/user/fhz_index";
	}
	/**
	 * 添加修改发货站信息
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("to_edit_fhz")
	public String toEditFhz(HttpServletRequest request, Model model){
        int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	UserFhz baseinfo = userService.getFhzById(id);
            model.addAttribute("baseinfo", baseinfo);
        }
		return "/maintain/user/fhz_edit";
	}
	/**
	 * 保存发货站信息
	 * @param request
	 * @param model
	 * @param fhz
	 * @return
	 */
	@RequestMapping("do_save_fhz")
	public String doSaveFhz(HttpServletRequest request, Model model,UserFhz fhz){
		fhz.setFhzdesc(fhz.getFhzdesc().trim());
		fhz.setFhzname(fhz.getFhzname().trim());
		fhz.setJianpin(fhz.getJianpin().trim());
		String res = "";
		try {
			userService.saveFhz(fhz);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/user/fhz_index.action";
	}
	/**
	 * 删除发货站信息
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("do_remove_fhz")
	public void doRemoveFhz(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				userService.removeFhz(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	//=====================客户

	/**
	 * 客户管理首页
	 * @param request
	 * @param model
	 * @param dto
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("customer_index")
	public String customerIndex(HttpServletRequest request, Model model,PagerDTO dto){
		List<Map> list = userService.searchCustomer(dto);
		model.addAttribute("list", list);

		model.addAttribute("_page", dto);
		return "/maintain/user/customer_index";
	}
	/**
	 * 根据id或简拼得到客户列表
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping("search_customer")
	public void searchUserCustomer(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		
		String q = request.getParameter("term");
		if(StringUtils.isBlank(q) || q.length()>6){//查询条件为空或字符数大于6(显示的汉字)时不予查询
			writer.print("");
			writer.flush();
			writer.close();
			return;
		}
		//System.out.println("aa==="+q);
		List list = new ArrayList();
		Map<String ,Object> map;
		PagerDTO dto = new PagerDTO();
		//
		if(RegexUtil.isNumeric(q)){//id
			dto.setS1(q);
		}else{//简拼
			dto.setS2(q);
		}
		List<Map> customerList = userService.searchCustomer(dto);
		if(customerList!=null && !customerList.isEmpty()){
			for(Map customer : customerList){
				map=new HashMap<String, Object>();
				map.put("id", customer.get("id"));
				map.put("label", customer.get("customername"));
				list.add(map);
			}
		}

		writer.print(JSONArray.fromObject(list.toArray()).toString());
		writer.flush();
		writer.close();
    }
	/**
	 * 到添加/修改客户的页面
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("to_edit_customer")
	public String toEditCustomer(HttpServletRequest request, Model model){
		//业务员列表
		List<UserYwy> ywyList = ywyCache.getYwyList();
		model.addAttribute("ywyList", ywyList);
		//地区列表
		List<Map<String,String>> areaList = AreaUtil.getAreaListForSel();
		model.addAttribute("areaList", areaList);
		int id = SuIntUtils.getInt(request.getParameter("id"));
        if(id>0){
        	UserCustomer baseinfo = userService.getCustomerById(id);
            model.addAttribute("baseinfo", baseinfo);
        }
		return "/maintain/user/customer_edit";
	}
	/**
	 * 保存业务员信息
	 * @param request
	 * @param model
	 * @param customer
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("do_save_customer")
	public String doSaveCustomer(HttpServletRequest request, Model model,UserCustomerDto customerDto){
		UserCustomer customer = customerDto.toEntity();
		String res = "";
		try {
			userService.saveCustomer(customer);
		} catch (Exception e) {
			log.error(e.getMessage());
			res = e.getMessage();
		}
		if(StringUtils.isNotBlank(res)){
			request.setAttribute("errorCode", res);
			return "su_error";
		}
		return "redirect:/admin/user/customer_index.action";
	}
	/**
	 * 删除客户信息
	 * @param request
	 * @param response
	 * @param model
	 * @throws Exception
	 */
	@RequestMapping("do_remove_customer")
	public void doRemoveCustomer(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int id = SuIntUtils.getInt(request.getParameter("id"));
		
		if(id==0){
			msgs.put("no id", "请选择要删除的数据");
		}else{
			String msg = "";
			try {
				userService.removeCustomer(id);
			} catch (Exception e) {
				log.error(e.getMessage());
				msg = e.getMessage();
			}
			if(StringUtils.isNotBlank(msg)){
				msgs.put("service error", msg);
			}else{
				msgs.put("success", "success");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }
	
	@RequestMapping("get_customer_info")
	public void getCustomerInfo(HttpServletRequest request,HttpServletResponse response, Model model){
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
        PrintWriter writer = null;
		try {
			writer = response.getWriter();
		} catch (IOException e) {
			log.error(e.getMessage());
		}
		if(writer == null)return;
		Map<String,String> msgs = new HashMap<String,String>();
		
		int customerId = SuIntUtils.getInt(request.getParameter("customerId"));
		
		if(customerId==0){
			msgs.put("errorMsg", "初始化客户数据时出错，请刷新页面重新操作");
		}else{
			UserCustomer customer = userService.getCustomerById(customerId);
			if(customer==null){
				msgs.put("errorMsg", "id为"+customerId+"的客户的信息出错，请检查");
			}else{
				msgs.put("ywyId", customer.getYwyid()+"");
				msgs.put("ywyName", ywyCache.getYwynameById(customer.getYwyid()));
				msgs.put("invoice", customer.getInvoice()+"");
			}
		}
		
		writer.print(JSONObject.fromObject(msgs));
		writer.flush();
		writer.close();
    }

}
